import { ResponseTask } from '@entities/Tasks'
import { TaskType } from '@entities/Tasks'
import moment from 'moment'
import { ReactNode } from 'react'
import { GridCardView } from './GridCardView/GridCardView'
import { ListCardView } from './ListCardView/ListCardView'
import styles from './TaskCard.module.scss'
moment.locale('ru')

interface TaskCardProps {
  onClick?: (task: ResponseTask) => void
  renderActions?: {
    renderDeleteBtn?: (task: ResponseTask) => ReactNode
    renderDoneBtn?: (task: ResponseTask) => ReactNode
  }
  renderTags?: (task: ResponseTask) => ReactNode
  task: ResponseTask
  view?: 'format_list_bulleted' | 'grid_view'
}

export const TaskCard = ({
  onClick,
  renderActions,
  renderTags,
  task,
  view = 'grid_view',
}: TaskCardProps) => {
  const { deadlineDate, tasks: subTasks, title } = task
  const { renderDeleteBtn, renderDoneBtn } = renderActions || {}
  const momentDueDate = moment(deadlineDate)
  const endingDate = moment(deadlineDate).format('DD MMMM YYYY').toString()
  const handlerTaskCardClick = () => {
    onClick?.(task)
  }
  const progress =
    subTasks &&
    subTasks.length > 0 &&
    subTasks?.reduce((res, task) => (task.type === TaskType.COMPLETED ? res + 1 : res), 0)
  const showProgressBar = subTasks && (progress === 0 || progress) && subTasks.length > 0

  return (
    <>
      {view === 'grid_view' ? (
        <GridCardView
          date={endingDate}
          dueDate={momentDueDate}
          onClick={handlerTaskCardClick}
          progress={progress || 0}
          renderActions={(task) => (
            <div className={styles['task-actions']}>
              {renderDoneBtn?.(task)}
              {renderDeleteBtn?.(task)}
            </div>
          )}
          renderTags={renderTags}
          showProgressBar={showProgressBar || false}
          subTasks={subTasks}
          task={task}
          title={title}
        />
      ) : (
        <ListCardView
          dueDate={momentDueDate}
          onClick={handlerTaskCardClick}
          progress={progress || 0}
          renderDeleteBtn={renderDeleteBtn}
          renderDoneBtn={renderDoneBtn}
          renderTags={renderTags}
          subTasks={subTasks}
          task={task}
          title={title}
        />
      )}
    </>
  )
}
